// lgc 标识用户身份




$(async function () {


    var url = urlParse();
    var { gid } = url;
    if (gid) {
        var result = await goodssearchlist({ gid });
        var { status, msg, sql } = result;
        if (status) {
            var { goodsName, goodsImg, goodsPrice, smallPicList, bigPicList, goodsDetail } = sql;

            // left  

            var switchListHTML = "";
            smallPicList.forEach((img, index) => {
                switchListHTML += `<li><img src="https:${img}" bigUrl="${bigPicList[index]}" alt=""></li>`
            })

            $(".wrapAll .left").html(`<div class="wrapInner">
                <div class="shadow"></div>
                <img class="smallImg"
                    src="${bigPicList[0]}"
                    alt="">
            </div>
            <ul class="switchList">
                ${switchListHTML}
            </ul>`);

            // right 
            $(".wrapAll .right").html(`<div class="scaleBar">
                    <img class="bigImg"
                        src="${bigPicList[0]}"
                        alt="">
                    </div>
                   
            <div class="goodsInfo">
            <div class="sku-name">
            ${goodsName}
            </div>
            <p class="sku-e">【即刻预定，锁定18号0点！13升爆款到手2699元】保价全网，买贵退差！咨询客服有惊喜，高速进口升级CPU ，恒温升级，香槟金外观，高端大气！</p>
            <div class="summary">
                <div>预售价</div>
                <div>
                    <span>￥ ${goodsPrice}</span>
                    <p><span class="q1">加入会员，下单约返16.99元云钻</span><span><a href="">立即开通</a></span></p>
                </div>
            </div>
            <div class="decilne">
                <div>优惠</div>
                <div>
                    <p>付定金减600元，到手价2799元</p>
                    <p><span>满100减10</span><a href="">共1张优惠券></a></p>
                    <p><span>100%刮中券，最高50元无敌券</span><a href="">立即去刮奖></a></p>
                    <p><span>实名认证领苏宁支付券</span><a href="">登录后查看 ></a></p>
                    <p>预计返169云钻</p>
                </div>
            </div>
            <div class="desro">
                <div>送至</div>
                <div>
                    <p>湖北武汉江岸区全区</p>
                    <p>免运费</p>
                </div>
            </div>
            <div class="series">
                <div>系列</div>
                <div>
                    <p><img src="../img/x1.jpg" alt="">【爆款】QC05智慧芯系列(天...</p>
                    <p><img src="../img/x2.jpg" alt="">【热销】QS41无忧芯系列(天...</p>
                    <p><img src="../img/x3.jpg" alt="">【爆款】QC05智慧芯系列(天...</p>
                    <p><img src="../img/x4.jpg" alt="">【热销】QS41无忧芯系列(天...</p>
                </div>
            </div>
            <div class="num-input">
                <div>数量</div>
                <div>
                    <a href="javascript:;" class="reduce">-</a>
                    <input type="text" class="count-input" value="1">
                    <a href="javascript:;" class ="add">+</a>
                </div>
            </div>
            <div class="buy">
                <button class="addToShoppingCar1">立即结算</button>
                <button class="addToShoppingCar">加入购物车</button>
            </div>
        </div>`);



            $(".goodsDetail").html(goodsDetail);


        } else {
            location.href = "./index.html";
        }
    } else {
        location.href = "./index.html";
    }
    $(document).on("mouseenter", ".switchList li", function () {
        $(this).addClass("active").siblings().removeClass("active")
        var bigUrl = $(this).find("img").attr("bigUrl");
        $(".smallImg,.bigImg").prop("src", bigUrl);
    })




    if (document.cookie) {
        if (getcookie("lgc")) {
            $(".show").css({ display: "none" }).removeClass()
            $(".hide").css({ display: "block" })
            $(".hide a").eq(0).html(`欢迎你:${getcookie("lgc")}`)
        }
    }



    $(".a1").click(function () {
        deletecookie("lgc")
        location.href = "./index.html"
    })

    $(".series p").click(function () {
        $(this).addClass("active1").siblings().removeClass("active1")
    })

    $(".add").click(function () {
        var num = $(this).prev().val()
        num++
        $(this).prev().val(num)
    })

    $(".reduce").click(function () {
        var num = $(this).next().val();
        if (num == 1) {
            return false
        }
        num--
        $(this).next().val(num)
    })

    // 计算缩放比例
    var scale = parseInt(getstyle([...$(".bigImg")][0], "width")) / parseInt(getstyle([...$(".smallImg")][0], "width"));


    var maxleft = parseInt(getstyle([...$(".smallImg")][0], "width")) - parseInt(getstyle([...$(".shadow")][0], "width"));
    var maxtop = parseInt(getstyle([...$(".smallImg")][0], "height")) - parseInt(getstyle([...$(".shadow")][0], "height"));

    function getstyle(ele, key) {
        var k = window.getComputedStyle != undefined ? window.getComputedStyle(ele)[key] : ele.currentStyle[key];
        return k
    }

    $(".wrapInner").on("mousemove", function (event) {
        var event = event || window.event;
        var x = event.pageX - [...$(".wrapAll .left")][0].offsetLeft - $(".shadow").width() / 2;
        var y = event.pageY - [...$(".wrapAll .left")][0].offsetTop - $(".shadow").height() / 2;
        if (x <= 0) {
            x = 0;
        }
        if (x >= maxleft) {
            x = maxleft;
        }
        if (y <= 0) {
            y = 0;
        }
        if (y >= maxtop) {
            y = maxtop;
        }
        [...$(".shadow")][0].style.left = `${x}px`;
        [...$(".shadow")][0].style.top = `${y}px`;

        [...$(".bigImg")][0].style.left = `${-x * scale}px`;
        [...$(".bigImg")][0].style.top = `${-y * scale}px`;
    })


    $(".wrapInner").mouseenter(function () {
        [...$(".shadow")][0].style.display = "block";
        [...$(".scaleBar")][0].style.display = "block";
    })
    $(".wrapInner").mouseleave(function () {
        [...$(".shadow")][0].style.display = "none";
        [...$(".scaleBar")][0].style.display = "none";
    })


    // 点击加入购物车
    // 谁?   买了什么东西?  买了多少件
    // 谁?   =>当前登录的用户
    // 买了什么东西?   =>商品的相关信息(goodslist=>对应goodsId)
    // 买了几件    =>$(".count-input").val();


    $(document).on("click", ".addToShoppingCar", async function () {

        // 谁   =>当前登录的用户(判断用户是否登录)
        var yonghu = getcookie("lgc")
        if (yonghu) {//用户已登录=>加入购物车(存数据库)
            var buynum = $(".count-input").val()
            var result = await addtoshopcar({ user: yonghu, gid, buynum })
            var { status, msg } = result;
            if (status) {
                if (confirm("商品加入购物车成功,是否进入购物车?")) {
                    location.href = "./shopcar.html?returnrul=" + encodeURIComponent(location.href)
                } else { }
            } else {
                alert(msg)
            }
        } else {//没有登录 =>去登陆

            // 问题
            // 没有登录=>去登陆=>登录成功(跳转主页)

            // 解决方法?
            // 跳转登录页的同时,传递当前页的url作为returnrul,登录成功再跳转回来


            location.href = "./login_account.html?returnrul=" + encodeURIComponent(location.href)
        }
    })


    $(document).on("click", ".shoptocar", async function () {
        location.href = "./shopcar.html"
    })

    $(document).on("click", ".addshop", async function () {
        history.back()
    })

    $(document).on("click", ".login", async function () {
        location.href = "./login_account.html"
        var yonghu = getcookie("lgc")
        console.log(yonghu);
        if (!yonghu) {
            location.href = "./login_account.html?returnrul=" + encodeURIComponent(location.href)
        }
    })
    $(".searchBtn").click(function () {
        if ($(".searchCon").val()) {
            location.href = `./goodslist.html?key=${$(".searchCon").val()}`
        }
    })

    $(".addToShoppingCar1").click(async function () {

        // 谁   =>当前登录的用户(判断用户是否登录)
        var yonghu = getcookie("lgc")
        if (yonghu) {//用户已登录=>加入购物车(存数据库)
            var buynum = $(".count-input").val()
            var result = await addtoshopcar({ user: yonghu, gid, buynum })
            var { status, msg } = result;
            if (status) {
                location.href = "./shopcar.html?returnrul=" + encodeURIComponent(location.href)
            } else {
                alert(msg)
            }
        } else {//没有登录 =>去登陆
            location.href = "./login_account.html?returnrul=" + encodeURIComponent(location.href)
        }
    })

})



function urlParse() {
    var search = location.search;
    var data = {};
    if (search) {  //从注册页跳转过来  => 有数据
        var str = search.substring(1);
        var list = str.split("&");
        // console.log(list);
        list.forEach(function (item) {
            var key = item.split("=")[0];
            var val = item.split("=")[1];
            data[key] = val;
        })
    }
    return data;
}



